import http from "@/utils/http";
import { Button, Divider, Form, Icon, Input, InputNumber, Layout, Spin, Tooltip, Upload, message } from "antd";
import axios from "axios";
import React from "react";
import MarkdownEditor from "@/utils/vditor";
import result from "@/locales/en-US/result";

const Req = axios.create({
	// baseURL: '',
	// withCredentials: true,
});

class DocParsing extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      fieldList:[
        {
          fieldName:"pdf_pwd",
          required:false,
          fieldType:'string',
          desc:"当pdf为加密文档时，需要提供密码。 备注：对前端封装该接口时，需要自行对密码进行安全防护。"
        },
        {
          fieldName:"dpi",
          required:false,
          fieldType:'integer',
          desc:"pdf文档的坐标基准,默认72dpi,推荐72或者144dpi"
        },
        {
          fieldName:"page_start",
          required:false,
          fieldType:'integer',
          desc:"当上传的是pdf时，page_start 表示从第几页开始转"
        },
        {
          fieldName:"page_count",
          required:false,
          fieldType:'integer',
          desc:"当上传的是pdf时，page_count 表示要进行转换的pdf页数。 不指定时，最大转换前24页。总页数不得超过1000页"
        },
        {
          fieldName:"apply_document_tree",
          required:false,
          fieldType:'integer',
          desc:"是否生成标题",
          descList:['0 不生成','1 生成标题"'],
          initialValue:1
        },
        {
          fieldName:"markdown_details",
          required:false,
          fieldType:'integer',
          desc:"是否生成markdown detials",
          descList:['0 不生成','1 生成']
        },
        {
          fieldName:"table_flavor",
          required:false,
          fieldType:'string',
          desc:"markdown里的表格格式",
          descList:['md 按md语法输出表格','html 按html语法输出表格'],
          initialValue:'md'
        },
        {
          fieldName:"get_image",
          required:false,
          fieldType:'string',
          desc:"获取markdown里的图片",
          descList:['none 不返回任何图像','page 返回每一页的整页图像','objects 返回页面内的图像对象','both 返回整页图像和图像对象'],
          initialValue:'both'
        },
        {
          fieldName:"parse_mode",
          required:false,
          fieldType:'string',
          desc:"是否强制使用OCR识别",
          descList:['auto 综合识别和解析方案','scan 仅按文字识别方式处理'],
          initialValue:2
        }
      ],
      fileInfo:{},
      result:"",
      loading:false
    }
  }

  doValidate = () => {
    const { form:{validateFields} } = this.props;
    validateFields((error,values) => {
      if(!error){
        this.doSubmit(values)
      }
    })
  }

  doSubmit = async values => {
    console.log(values);
    const { fileInfo } = this.state;
    const formData = new FormData();
    formData.append('file', fileInfo.originFileObj);
    for(const item in values){
      if(values[item] != undefined && values != '' && values[item] != null){
        formData.append(item, values[item]);
      }
      
    }
    this.setState({
      loading:true,
      result:""
    },async () => {
      const res = await this.doRequest(formData)
      this.setState({
        result:res.data,
        loading:false
      })
    })
    
  }

  doRequest = (params) => {
    return http.uploadFile('/textin/get',params)
  }

  previewFile = () => {
    const { fileInfo } = this.state;
    const that = this;
    var blobURL = URL.createObjectURL(fileInfo.originFileObj);
    window.open(blobURL,'_blank');
  }

  render(){
    const { fieldList,fileInfo ,result,loading} = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    const that = this;
    const uploadProps = {
      name: 'file',
      showUploadList:false,
      accept:".png,.jpg,.jpeg,.pdf,.bmp,.tiff",
      onChange(info) {
        console.log(info);
        that.setState({
          fileInfo:info.file
        })
        
      },
      customRequest(){
        console.log('自定义上传');
      }
    };
    const renderLabel = item => (
      <label style={{textAlign:"left"}}>
        <label>{item.fieldName}</label>
        <Tooltip placement='right' title={
          <div>
            <h3 style={{color:"#ffffff"}}>{item.fieldName}</h3>
            <Divider style={{margin:"10px 0"}} />
            <div>
              <label>必填：</label>
              <label>{item.required ? '是' : '否'}</label>
            </div>
            <div>
              <label>类型：</label>
              <label>{item.fieldType}</label>
            </div>
            <div>
              <label>描述：</label>
              <label>{item.desc}</label>
            </div>
            {
              item.descList ? (
                <div style={{marginLeft:40}}>
                  {item.descList.map((d,i) => {
                    return <div key={i}>{d}</div>
                  })}
                </div>
              ) : ''
            }
            
          </div>
        }>
          <Icon type="question-circle" style={{verticalAlign:"middle",marginLeft:5}} />
        </Tooltip>
      </label>
    )
    return (
      <div style={{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"auto",background:"#ffffff",padding:10}}>
        <Spin spinning={loading}>
          <Layout style={{background:"#ffffff !important"}}>
            <Layout.Sider theme='light' width={500} style={{padding:10}}>
              <Upload {...uploadProps}>
                <Button type="upload">上传文件</Button>
              </Upload>
              <div style={{marginBottom:10}}>
                {
                  fileInfo.name ? <span onClick={this.previewFile} style={{color:"blue",cursor:"pointer"}}>{fileInfo.name}</span> : ''
                }
              </div>
              <Form {...formItemLayout}>
                <h2>HTTP Header</h2>
                <Form.Item label='x-ti-app-id'>
                  {getFieldDecorator("appId",{rules:[{required:true,message:"请输入"}],initialValue:"4c2ea0319c1246698f6cb0bd422a8031"})(
                    <Input placeholder="必填" />
                  )}
                </Form.Item>
                <Form.Item label='x-ti-secret-code'>
                  {getFieldDecorator("secret",{rules:[{required:true,message:"请输入"}],initialValue:"512d92085fb854ad3186b48a18954c20"})(
                    <Input placeholder="必填" />
                  )}
                </Form.Item>
                <h2>URL参数</h2>
                {
                  fieldList.map((item,index) => {
                    return (
                      <Form.Item {...formItemLayout} label={renderLabel(item)} key={index}>
                        {
                          getFieldDecorator(item.fieldName,{rules:[{required:item.required,message:"请输入"}],initialValue:item.initialValue})(
                            item.fieldType == 'integer' ? <InputNumber style={{width:"100%"}} /> : <Input />
                          )
                        }
                      </Form.Item>
                    )
                  })
                }
                
              </Form>
              <div style={{textAlign:"center"}}>
                <Button type="primary" onClick={this.doValidate}>发起调用</Button>
              </div>
              
            </Layout.Sider>
            <Layout.Content style={{paddingLeft:10}}>
                <div>
                  {
                    result ? (
                      <MarkdownEditor
                        value={result}
                        title={fileInfo.name}
                        name='markdown-editor'
                        id='markdown-editor'
                        height='calc(100vh - 50px)'
                        width='700'
                        onChange={(value, type) => {
                          switch (type) {
                            case 'content':
                              this.setState({ result: value });
                              break;
                            case 'title':break;
                          }
                        }}
                        ref={(r) => (this.vEditor = r)}
                      />
                    ) : ''
                  }
                  
                </div>
            </Layout.Content>
          </Layout>
        </Spin>
      </div>
    )
  }
}

export default Form.create()(DocParsing)